package com.ice.framwork.rocketmq.util;

import com.alibaba.fastjson.JSON;
import com.yomahub.tlog.context.TLogContext;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

import java.util.UUID;

/**
 * @author wangwei
 * @Date 2023/8/17 11:31
 */
public class RocketMqMessageBuilder {

    /**
     *
     **/
    public static Message<String> getMessage(Object object) {
        String payload = JSON.toJSONString(object);
        Message<String> message = MessageBuilder.withPayload(payload)
                .setHeader("tlogTraceId", TLogContext.getTraceId())
                .setHeader("tlogSpanId", TLogContext.getSpanId())
                .build();
        return message;
    }

    public static Message<String> getTransactionMessage(Object object, Class serviceClass) {
        // 最终一致性事务编号
        String txNo = UUID.randomUUID().toString().replace("-", "");
        String payload = JSON.toJSONString(object);
        Message<String> message = MessageBuilder.withPayload(payload)
                .setHeader("serviceClassName", serviceClass.getName())
                .setHeader("tlogTraceId", TLogContext.getTraceId())
                .setHeader("tlogSpanId", TLogContext.getSpanId())
                .setHeader(RocketMQHeaders.KEYS, txNo)
                .setHeader(RocketMQHeaders.TRANSACTION_ID, txNo)
                .build();
        return message;
    }
}
